package com.chris.datacnter.controller;

import com.chris.datacnter.dto.BaseException;
import com.chris.datacnter.dto.ChrisException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局拦截contorller类
 * 注：404被tomcat容器拦截了到不了controller也就到不了@ControllerAdvice
 * 苏斌 2022-3-15
 */
@ControllerAdvice
public class WebAdeviceController {

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder

    @InitBinder
    public void initWebBinder(WebDataBinder binder){

    }*/

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model

    @ModelAttribute
    public void addAttribute(Model model) {
        model.addAttribute("attribute",  "The Attribute");
    }  */


    /**
     * 拦截500
     * @param request
     * @param e
     * @return

     @ExceptionHandler
     @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ModelAndView handleCustomException(HttpServletRequest request, Exception e) {
     ModelAndView mv = new ModelAndView();
     mv.addObject("code",500);
     mv.addObject("message", e.getMessage());
     mv.addObject("StackTrace", e.getStackTrace());
     mv.setViewName("/error/500");
     return mv;
     //request.setAttribute("error", e);
     // return "servererror";
     }
     */


    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(ChrisException.class)
    @ResponseBody
    @ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseException handleChrisException(ChrisException e) {
        BaseException ex = new BaseException();
        ex.setCode(e.getCode());
        ex.setMessage(e.getMessage());
        ex.setDescribe(e.getDescribe());
        return ex;
    }

    /**
     * 通用错误类
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseException handleCustomException(HttpServletRequest request, Exception e) {
        BaseException ex = new BaseException();
        ex.setCode(500);
        ex.setMessage(e.getMessage());
       // ex.setDescribe(e.toString());
        //ex.setStackTrace(e.getStackTrace());
        return ex;
    }

}
